package com.jeesite.modules.digitalize.service;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.jeesite.common.lang.ObjectUtils;
import com.jeesite.common.lang.StringUtils;
import com.jeesite.modules.digitalize.config.Constants;
import com.jeesite.modules.digitalize.dao.DigitalizeResourceLibraryDao;
import com.jeesite.modules.digitalize.entity.DigitalizeResourceLibrary;
import com.jeesite.modules.digitalize.entity.ResourceLibrary;
import com.jeesite.modules.digitalize.entity.dto.component.ComponentReNameDto;
import com.jeesite.modules.digitalize.entity.dto.resource.ResourceAddDto;
import com.jeesite.modules.digitalize.entity.dto.resource.ResourceDelDto;
import com.jeesite.modules.digitalize.entity.dto.resource.ResourceMoveDto;
import com.jeesite.modules.digitalize.entity.vo.resource.ResourcesVo;
import com.jeesite.modules.digitalize.util.response.ResultStatusCode;
import com.jeesite.modules.digitalize.util.response.ResultVo;
import com.jeesite.modules.sys.utils.UserUtils;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.RequestBody;

import javax.annotation.Resource;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;
import java.util.stream.Collectors;

/**
 * (DigitalizeResourceLibrary)表服务实现类
 *
 * @author xk
 * @since 2024-01-03 14:31:12
 */
@Service("digitalizeResourceLibraryService")
public class DigitalizeResourceLibraryService extends ServiceImpl<DigitalizeResourceLibraryDao, DigitalizeResourceLibrary> {

    @Resource
    DigitalizeResourceLibraryDao digitalizeResourceLibraryDao;

    /**
     * @date 2024年01月03日 17:24:35
     * @author patronli
     * @Description: 返回文件列表
     */
    public ResultVo<List<ResourcesVo>> files(String projectCode, String fileName) {
        List<ResourcesVo> list = new ArrayList<>();
        LambdaQueryWrapper<DigitalizeResourceLibrary> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(DigitalizeResourceLibrary::getProjectCode, projectCode);
        queryWrapper.eq(DigitalizeResourceLibrary::getDelStatus, Constants.DEL_STATUA_0);
        if (StringUtils.isNotEmpty(fileName)) {
            queryWrapper.like(DigitalizeResourceLibrary::getFileName, fileName);
        }
        List<DigitalizeResourceLibrary> digitalizeResourceLibraryList = this.list(queryWrapper);
        if (!CollectionUtils.isEmpty(digitalizeResourceLibraryList)) {
            for (DigitalizeResourceLibrary digitalizeResourceLibrary : digitalizeResourceLibraryList) {
                list.add(new ResourcesVo(digitalizeResourceLibrary.getId().intValue(), digitalizeResourceLibrary.getParentId(), digitalizeResourceLibrary.getFileType(), digitalizeResourceLibrary.getFileName(), digitalizeResourceLibrary.getFileUrl(), digitalizeResourceLibrary.getCreateDate()));
            }
            list = buildDataTree(list, Integer.parseInt(Constants.DEFAULT_TOP_PARENT_ID));
        }
        return ResultVo.success(list);
    }

    /**
     * @param dto
     * @date 2024年01月03日 17:26:04
     * @author patronli
     * @Description: 上传文件 或者创建文件夹
     */
    public ResultVo addFloder(ResourceAddDto dto) {
        Integer fileType = dto.getFileType();
        DigitalizeResourceLibrary resourceLibrary;
        if (Constants.type_0.equals(fileType)) {//创建的是文件夹
            resourceLibrary = new DigitalizeResourceLibrary(dto.getParentId(),dto.getProjectCode(), dto.getFileName(), fileType);
            resourceLibrary.setFileUrl(dto.getFileUrl());
        } else {//创建的是文件
            //截取文件名字
            String fileUrl = dto.getFileName();
            String fileName = fileUrl.substring(fileUrl.lastIndexOf("/") + 1);
            resourceLibrary = new DigitalizeResourceLibrary(dto.getParentId(),dto.getProjectCode(), fileName, fileType, fileUrl);
            resourceLibrary.setFileUrl(dto.getFileUrl());
        }
        this.save(resourceLibrary);
        return ResultVo.success();
    }

    public ResultVo moveFile(@Validated @RequestBody ResourceMoveDto dto) {
        List<Long> ids = dto.getIds();
        Integer parentId = dto.getParentId();
        if (ids.contains(Long.valueOf(parentId))) {
            return ResultVo.failure(ResultStatusCode.MOVE_FILE_ERROR_1.getCode(), ResultStatusCode.MOVE_FILE_ERROR_1.getMsg());
        }
        ids.forEach(e -> {
            DigitalizeResourceLibrary resourceLibrary = new DigitalizeResourceLibrary();
            resourceLibrary.setId(e);
            resourceLibrary.setParentId(parentId);
            this.updateById(resourceLibrary);
        });
        return ResultVo.success();
    }

    /**
     * @param dto
     * @date 2024年01月03日 17:35:34
     * @author patronli
     * @Description: 删除到回收站
     */
    public ResultVo delFile(ResourceDelDto dto) {
        dto.getIds().forEach(id -> {
            String delBatch = UUID.randomUUID().toString().replaceAll("-", "");
            DigitalizeResourceLibrary resourceLibrary = new DigitalizeResourceLibrary(Constants.DEL_STATUA_2, delBatch);
            resourceLibrary.setId(id);
            this.updateById(resourceLibrary);
            List<ResourceLibrary> childList = digitalizeResourceLibraryDao.getChildList(id);
            if (CollUtil.isNotEmpty(childList)) {
                childList.forEach(child -> {
                    DigitalizeResourceLibrary childResourceLibrary = new DigitalizeResourceLibrary(Constants.DEL_STATUA_2, delBatch);
                    childResourceLibrary.setId(child.getId());
                    this.updateById(childResourceLibrary);
                });
            }
        });
        return ResultVo.success();
    }


//                resourcesVo.setId(digitalizeResourceLibrary.getId());
//                resourcesVo.setParentId(digitalizeResourceLibrary.getParentId());
//                resourcesVo.setFileName(digitalizeResourceLibrary.getFileName());
//                resourcesVo.setFileUrl(digitalizeResourceLibrary.getFileUrl());
//                resourcesVo.setFileType(digitalizeResourceLibrary.getFileType());
//                resourcesVo.setCreateDate(digitalizeResourceLibrary.getCreateDate());


    public List<ResourcesVo> buildDataTree(List<ResourcesVo> datas, Integer parentId) {
        List<ResourcesVo> source = datas.stream().filter(e -> e.getParentId().equals(parentId)).collect(Collectors.toList());
        if (CollectionUtils.isEmpty(source)) {
            return null;
        }
        List<ResourcesVo> tree = new ArrayList<>();
        source.forEach(item -> {
            if (item.getParentId().equals(parentId)) {
                List<ResourcesVo> children = buildDataTree(datas, item.getId());
                tree.add(new ResourcesVo(item.getId(), item.getParentId(), item.getFileType(), item.getFileName(), item.getFileUrl(), item.getCreateDate(), children));
            }
        });
        return tree;
    }

    public ResultVo reName(ComponentReNameDto dto) {
        DigitalizeResourceLibrary component = this.baseMapper.selectById(dto.getId());
        if (ObjectUtils.isEmpty(component)) {
            return ResultVo.failure("暂未找到对应文件！");
        }
        if (!Constants.type_0.equals(component.getFileType())) {
            return ResultVo.failure("仅支持修改文件夹名称！");
        }
        LambdaUpdateWrapper<DigitalizeResourceLibrary> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.set(DigitalizeResourceLibrary::getFileName, dto.getFileName());
        updateWrapper.set(DigitalizeResourceLibrary::getUpdateDate, new Date());
        updateWrapper.set(DigitalizeResourceLibrary::getUpdateBy, UserUtils.getUser().getId());
        updateWrapper.eq(DigitalizeResourceLibrary::getId, dto.getId());
        this.update(updateWrapper);
        return ResultVo.success();
    }

    public DigitalizeResourceLibrary getByIdAndDelStatus(Integer id) {
        return this.baseMapper.getByIdAndDelStatus(id);
    }

    public void updateByIdAndDelStatus(DigitalizeResourceLibrary library) {
        this.baseMapper.updateByIdAndDelStatus(library);
    }

    public void updateDel(DigitalizeResourceLibrary library) {
        this.baseMapper.updateDel(library);
    }
}

